import axios from 'axios'
const cartModules = {
    namespaced: true,
    state: {
        list: []
    },
    // 给list赋值
    mutations: {
        setStates(state, val) {
            state.list = val
        },
        // 1111
        // // 全选影响单选
        // click(state, val) {
        //     // console.log(val);
        //     state.list.map((e) => {
        //         e.goods_state = val;
        //     });
        // }

        // 222 单选影响全选
        setGoodsItem(state, obj) {
            state.list[obj.index].goods_state = obj.checked
        },
        setGoodsList(state) {
            state.list.every((obj) => {
                return obj.goods_state == true;
            });
        },
        setRed(state, obj) {
            if (state.list[obj.index].goods_count < 1) {
                state.list[obj.index].goods_count = 0;
            } else {
                state.list[obj.index].goods_count--
            }
        },
        addD(state, obj) {
            state.list[obj.index].goods_count++
        }
    },
    // 发送ajax
    actions: {
        async getList(store) {
            const res = await axios({
                url: "/api/cart",
            })
            this.list = res.data.list;
            store.commit('setStates', res.data.list)
        }
    },
    getters: {
        // 总价、总数量
        allCount(state) {
            return state.list.reduce((sum, e) => {
                if (e.goods_state) {
                    sum += e.goods_count;
                }
                return sum;
            }, 0);
        },
        allPrice(state) {
            return state.list.reduce((sum, e) => {
                if (e.goods_state) {
                    sum += e.goods_count * e.goods_price;
                }
                return sum;
            }, 0);
        },
        // 1111
        // // 全选影响单选
        all(state) {
            return state.list.every((obj) => {
                return obj.goods_state == true;
            });
        },
    }
}
export default cartModules